<?php
echo "Please enter the system user: ";
$user = trim(fgets(STDIN));

echo "Please enter the system group: ";
$group = trim(fgets(STDIN));

echo "Please enter the domain name: ";
$domain = trim(fgets(STDIN));

$base_directory = exec('cd ../../ && pwd');

$lighttpd_configuration_template = file_get_contents('lighttpd.conf');
echo "Writing lighttpd configuration...";
$lighttpd_configuration = str_replace(
  Array(
    'var.base-directory =',
    'var.domain =',
    'server.username =',
    'server.groupname =',
  ),
  Array(
    "var.base-directory = \"$base_directory/\"",
    "var.domain = \"$domain\"",
    "server.username = \"$user\"",
    "server.groupname = \"$group\"",
  ),
  $lighttpd_configuration_template
);
file_put_contents('../../config/lighttpd.conf', $lighttpd_configuration);
echo "done!\n";


echo "Please enter the root password of the MySQL server: ";
$mysql_root_password = trim(fgets(STDIN));

echo "Please specify the password of the Twimight Server user to "
."connect to MySQL: ";
$mysql_user_password = trim(fgets(STDIN));

$db_setup_template = file_get_contents('database_setup.sql');
$db_setup = str_replace(
  "CREATE USER 'twimight_server'@'localhost' IDENTIFIED BY  '';",
  "CREATE USER 'twimight_server'@'localhost' IDENTIFIED BY  '$mysql_user_password';",
  $db_setup_template
);
file_put_contents('database_setup_with_password.sql', $db_setup);

$config_template = file_get_contents('config.ini');
$config = str_replace(
  "        password =",
  "        password =\"$mysql_user_password\"",
  $config_template
);
file_put_contents('../../config/config.ini', $config);

echo "Setting up database...";
exec("mysql -u root -p$mysql_root_password < database_setup_with_password.sql");
echo "done!\n";

exec("chown -R $user:$group $base_directory");

file_put_contents('crontab.txt', '@daily '.$base_directory.'/scripts/background/cron.sh');

echo "Please remove this install folder from your production environment!\n";
echo "Please add the 'crontab.txt' content to the cron jobs of user $user!\n";
echo "\nDONE.\n"
?>